package com.itheima.travel.controller;

import com.itheima.travel.domain.*;
import com.itheima.travel.service.RouteService;
import com.itheima.travel.utils.CartUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private RouteService routeService;

    @Autowired
    private CartUtils cartUtils;


    @RequestMapping("/addCart")
    public ResultInfo addCart(Integer num, Integer rid, HttpSession session){
        //从会话域获取用户对象
        User user = (User) session.getAttribute("user");
        //调用工具类获取当前用户对象的购物车
        Cart cart = cartUtils.getCartFromRedis(user);
        //获取当前用户购物车内所有的购物车项集合
        LinkedHashMap<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        //通过rid获取获取购物车项
        CartItem cartItem = cartItemMap.get(rid);
        //判断购物车项是否存在
        if (cartItem!=null){
            //若购物车项存在，更新当前购物车项数量
            cartItem.setNum(cartItem.getNum()+num);
        }else {
            //若购物车项不存在，创建一个新购物车项
            Route route = routeService.findRouteByRid(rid);
            cartItem = new CartItem();
            cartItem.setNum(num);
            cartItem.setRoute(route);
            cartItemMap.put(rid,cartItem);
        }
        cartUtils.setCartToRedis(user,cart);
        return new ResultInfo(true,"添加购物车成功",cartItem);
    }

    @RequestMapping("/findAll")
    public ResultInfo findAll(HttpSession session){
        //1. 从session中获取user对象
        User user = (User) session.getAttribute("user");
        //2. 从redis中获取cart对象
        Cart cart = cartUtils.getCartFromRedis(user);
        //3. 封装到结果对象中返回
        return new ResultInfo(true,"查看成功",cart);
    }

    @RequestMapping("/deleteCartItem")
    public ResultInfo deleteCartItem(Integer rid,HttpSession session){
        //1. 从会话中获取用户对象
        User user = (User) session.getAttribute("user");
        //2. 从redis中获取cart对象
        Cart cart = cartUtils.getCartFromRedis(user);
        //3. 得到所有的购物车项
        LinkedHashMap<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        //4. 通过rid删除其中一项
        cartItemMap.remove(rid);
        //5. 更新cart到redis中
        cartUtils.setCartToRedis(user,cart);
        //6. 返回cart对象
        return new ResultInfo(true,"删除成功",cart);
    }
}
